//格式化时间戳
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


//判断是打开还是保存在打开
const goifOpen = (e)=> {
  
  if (!e.url){
    wx.showToast({
      title: 'url为空',
      icon:'none'
    })
    return;
  }
  wx.getStorage({
    key: String(e.id),
    success: function(res) {
      if (res.data) {
        // console.log('后面打开')
        // console.log(res.data)
        
        //type   0视频  1  文档   2  目录
        if(e.type == '0'){
          wx.navigateTo({ url: '/pages/classDetail/index?url=' + res.data.path })
        }else{
          openDoc(res.data.path)
        }
      } else {
        saveFile(e)
      }
    },
    fail(err){
      saveFile(e)
    }
  })
}
//打开文档
const openDoc = (_filePath)=>{
  wx.openDocument({
    filePath: _filePath,
    fail(err){
      console.log(err);
      wx.showToast({ title:'源文件不存在'+ JSON.stringify(err),icon:'none',duration:3000})
    }
  })
}

//保存文档
const saveFile = (params)=>{
  const _fileUrl = params.url;
  const _id = params.id;
  const _name = params.name;

  const vm = this;
  // console.log(_fileUrl)

  if(params.type=='0'){
    wx.setStorage({
      key: String(_id),
      data: {
        path:_fileUrl,
        name:_name,
        type:params.type,
        id:_id
      }
    })
    goifOpen(params)
  }else{
    const downloadTask = wx.downloadFile({
      url: _fileUrl,
      success(res) {
        //关掉loading
        // setTimeout(() => { wx.hideToast() }, 200)
        //把临时路径存起来 key用id
        // console.log('临时路径'+res.tempFilePath)
        //把文件存在本地，并且把路径放到storage里面
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success(savedFilePath) {
            wx.setStorage({
              key: String(_id),
              data: {
                path:savedFilePath.savedFilePath,
                name:_name,
                type:params.type,
                id:_id
              }
            })
            // console.log('第一次打开')
            openDoc(savedFilePath.savedFilePath)
          },
          fail(err){
            wx.showToast({title:'保存文件失败'+ JSON.stringify(err),icon:'none',duration:10000})
          }
        })
      },
      fail: function(err) {
        // console.log(err);
        wx.showToast(err)
      }
    })
    wx.showToast({
      title: '已下载 0%',
      icon: 'loading',
      duration: 100000
    })
    downloadTask.onProgressUpdate((res) => {
      // console.log('下载进度', res.progress)
      wx.showToast({
        title: '已下载 ' + String(res.progress) + '%',
        icon: 'loading',
        duration: 100000
      })
      // console.log('已经下载的数据长度', res.totalBytesWritten)
      // console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
    }) 
  }
}

//收藏文件
const goCollection = (id,callback)=>{
  wx.getStorage({
      key:'userInfo',
      success:function(e){
        wx.request({
          url: 'https://www.bchzh.xin/hzmobilework/app/fileClassification/collectionFiles',
          // url: 'http://192.168.0.30:8080/hzmobilework/app/fileClassification/collectionFiles',
          data: {classificationId:id,userId:e.data.id},
          header: {'content-type': 'application/json'},
          success(res) {
            // console.log(res.data.data.list);
            callback&&callback()
            // Toast.success('已收藏');
            wx.showToast({
              title: '已收藏',
              icon: 'success',
              duration: 3000
            })
            
          }
        })
      }
  })
}
//加入阅读量接口
const readliang = (id,callback)=>{
    wx.request({
      url: 'https://www.bchzh.xin/hzmobilework/app/fileClassification/read',
      // url: 'http://192.168.0.30:8080/hzmobilework/app/fileClassification/read',
      data: {classificationId:id},
      header: {'content-type': 'application/json'},
      success(res) {
        callback&&callback()
      }
    })
}



module.exports = {
  formatTime: formatTime,
  saveFile: saveFile,
  openDoc: openDoc,
  goifOpen: goifOpen,
  goCollection: goCollection,
  readliang: readliang
}
